import { camelCase, forEach, get, upperCase } from "lodash-es";
import { ClientInstance, createClient } from "./client";
import queryString from "query-string";

type TaskOptions = {
  [title: string]: {
    inputs: Record<string, any>;
  };
};

export const createTask = (
  client: ReturnType<typeof createClient>,
  prompt: any,
  options: TaskOptions
) => {
  // 处理工作流输入绑定
  const processedPrompt = applyOptions(JSON.parse(JSON.stringify(prompt)), options);

  const start = async ({
    resultType
  }:{ resultType?: string } = {}): Promise<string[] | undefined> => {
    return new Promise(async (resolve, reject) => {
      try {
        const { promptId } = await client.createPrompt(processedPrompt);
        // 设置事件监听

        client.once('execution_success', async (data) => {
          const res = await client.getHistory(promptId);
          const promptResult = res[camelCase(promptId)]
          const output: any = promptResult?.outputs[
            getNodeCodeByTitle(prompt, "output")
          ] as any[];


          if (resultType === 'images') {
            
            const newImgs = output.images.map((item: any) =>
              queryString.stringifyUrl({
                url: `/image`,
                query: item,
              }),
            );
            resolve(newImgs);
          }
          resolve(undefined);
        })

        client.once('execution_error', async (data) => {
          reject('生成错误，请重试');
        })

        // const onFailed = (data: { taskId: string, error: string }) => {
        //   if (data.taskId === taskId) {
        //     client.off('task_completed', onCompleted);
        //     client.off('task_failed', onFailed);
        //     reject(new Error(data.error));
        //   }
        // };

        // client.on('task_completed', onCompleted);
        // client.on('task_failed', onFailed);
      } catch (error) {
        reject(error);
      }
    });
  };

  return { processedPrompt, start };
};

export const getNodeCodeByTitle = (json: any, title: string) => {
  let result = "0";

  forEach(json, (value, key, obj) => {
    if (get(value, "_meta.title") === title) {

      result = key;
    }
  });

  return result;
};
function applyOptions(prompt: any, options: TaskOptions): any {
  // 根据title查找并更新节点inputs
  for (const nodeId in prompt) {
    const node = prompt[nodeId];
    if (node._meta?.title) {
      if (node._meta.title === 'seed') {
        // 为seed节点生成随机数 (保持与示例相同的数值范围)
        node.inputs.seed = Math.floor(Math.random() * 1000000000000000);
      } else if (options[node._meta.title]) {
        Object.assign(node.inputs, options[node._meta.title])
      }
    }
  }
  return prompt;
}
